package com.fly.common.exception;

import java.nio.charset.StandardCharsets;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import lombok.extern.slf4j.Slf4j;

/**
 * 统一异常处理器
 * 
 * @author 00fly
 * @version [版本号, 2018-09-11]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Slf4j
@Component
public class MyExceptionHandler implements HandlerExceptionResolver
{
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception)
    {
        if (isAjaxRequest(request))
        {
            // 设置ContentType
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.setCharacterEncoding(StandardCharsets.UTF_8.name());
            response.setHeader("Cache-Control", "no-cache, must-revalidate");
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            return null;
        }
        // 非ajax请求返回提示页
        request.setAttribute("ex", exception);
        if (exception instanceof DataException)
        {
            log.error(exception.getMessage(), exception);
            return new ModelAndView("/error-business");
        }
        return new ModelAndView("/error");
    }
    
    /**
     * 判断一个请求是否是Ajax请求
     * 
     * @param request
     * @return
     * @see [类、类#方法、类#成员]
     */
    public static boolean isAjaxRequest(HttpServletRequest request)
    {
        return request != null && "XMLHttpRequest".equals(request.getHeader("x-requested-with"));
    }
}
